<template>
    <el-upload
            class="img-upload"
            ref="upload"
            action="http://localhost:8443/api/admin/content/books/covers"
            with-credentials
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleSuccess"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
        <!--   slot="tip"   -->
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
</template>

<script>
    import {getCurrentInstance, reactive, toRefs} from "vue";

    export default {
        name: 'ImgUpload',
        setup() {
            const data = reactive({
                fileList: [],
                url: ''
            })
            let {proxy} = getCurrentInstance()

            function handleRemove(file, fileList) {
                console.log(file, fileList)
            }

            function handlePreview(file) {
                console.log(file)
                // 此处的 file 是整个文件
                // console.log(file.response)
            }

            function handleExceed(files, fileList) {
                console.log(fileList)
                proxy.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
            }

            function beforeRemove(file, fileList) {
                console.log(fileList)
                return this.$confirm(`确定移除 ${file.name}？`)
            }

            function handleSuccess(response) {
                data.url = response
                // console.log(this.url)
                proxy.$emit('onUpload')
                proxy.$message.warning('上传成功')
            }

            function clear() {
                proxy.$refs.upload.clearFiles()
            }

            return {
                ...toRefs(data),
                clear,
                handleSuccess,
                handleExceed,
                handlePreview,
                handleRemove,
                beforeRemove

            }
        }
    }
</script>

<style scoped>
    .img-upload {
        /*height: 200px;*/
    }
</style>
